package com.ling.util;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

public class SendEmailUtil {
    private static String apiUser;
    private static String apiKey;
    private static String from;
    private static String fromName;

    static {
        apiUser = "ericling";
        apiKey = "DnTImuiccv6vxseO";
        from = "zhiyun@zhiyuntech.top";
        fromName = "知云";
    }

    /**
     *
     * @param subject   发送邮件主题
     * @param html      发送邮件内容
     * @param to        邮件接收人
     * @throws Exception 抛出异常
     */
    public static void sendCommon(String subject, String html,String to) throws Exception {
        final String url = "http://api.sendcloud.net/apiv2/mail/send";
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("apiUser", apiUser));
        params.add(new BasicNameValuePair("apiKey", apiKey));
        params.add(new BasicNameValuePair("to", to));
        params.add(new BasicNameValuePair("from",from));
        params.add(new BasicNameValuePair("fromName", fromName));
        params.add(new BasicNameValuePair("subject", subject));
        params.add(new BasicNameValuePair("html", html));

        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        HttpResponse response = httpClient.execute(httpPost);

        // 处理响应
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 正常返回, 解析返回数据
            System.out.println(EntityUtils.toString(response.getEntity()));
        } else {
            System.err.println("error");
        }
        httpPost.releaseConnection();
    }

    public static void main(String[] args) {
        try {
            sendCommon("用户周订阅推送","<h1>此为测试数据</h1>","eric_ling@foxmail.com");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}